package com.asdc.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @ClassName GateFilter
 * @Author bsy
 * @Description : 自定义Filter 实现请求过滤
 * 1) 请求参数中含有 u=* 放行，
 * 2）其他形式的被认为 不符合要求
 * 测试：
 *  http://localhost:9527/payment/get/1         // {"status":"401","msg":User Non Unauthorized!"}
 *  http://localhost:9527/payment/get/1?u=z3    //{"code":200,"message":"查询成功,serverPort:  8002","data":{"id":1,"serial":"123"}}
 *
 * @Date 2021/12/12 15:51
 * @Version 1.0
 */
@Component
@Slf4j
public class MyDefineGateFilter implements GlobalFilter, Ordered {

    /**
     * 判断参数中是否含有u，如果没有显示非法用户，如果有就放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("-----MyDefineGateFilter.filter  coming ! Now : {}", new Date());
        String param = exchange.getRequest().getQueryParams().getFirst("u");
        if (param == null) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] bytes = "{\"status\":\"401\",\"msg\":User Non Unauthorized!\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
